package com.inight.nightojbackendgateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 *
 */
public class GlobalAuthFilter implements GlobalFilter, Ordered {

    // spring的. 用于匹配是否包含路径
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    // hutool 最后调用的也是spring的工具
    // private cn.hutool.core.text.AntPathMatcher ant = new cn.hutool.core.text.AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // return null;
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 路径中包含inner, 直接设置没权限, 因为 带 inner 的路径都是我们内部调用的
        if(antPathMatcher.match(("/**/inner/**"), path)) {
            // 直接设置 403. 并设置返回值
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.FORBIDDEN);
            // 设置一些返回信息
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("调用了内部接口, 没有权限".getBytes(StandardCharsets.UTF_8));
            // 返回
            return response.writeWith(Mono.just(dataBuffer));
        }
        // todo 统一权限校验, 通过 JWT 获取登录信息
        return chain.filter(exchange);
    }


    /**
     * 假如有多个过滤器, 就可以设置优先级. 0的优先级是最高的
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
